package fr.mistra.exercice.bibliotheque.presentation;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import fr.mistra.exercice.bibliotheque.dao.DAOException;
import fr.mistra.exercice.bibliotheque.services.AuthManager;
import fr.mistra.exercice.bibliotheque.services.BadLoginException;
import fr.mistra.exercice.bibliotheque.services.BadPasswordException;
import fr.mistra.exercice.bibliotheque.services.ServiceFactory;

/**
 * Servlet implementation class Authentification
 */
public class AuthentificationServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public AuthentificationServlet() {
        super();
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		System.err.println("On ne devrait pas arriver sur Authentification via du get !");
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		HttpSession session = request.getSession();
		
		String login = request.getParameter("login");
		String passwd = request.getParameter("passwd");
		
		AuthManager auth = ServiceFactory.getAuthManager();
		try {
			auth.authenticate(login, passwd);
			session.setAttribute("login", login);
			session.setMaxInactiveInterval(60);
			request.getRequestDispatcher("/JSP/Accueil.jsp").forward(request, response);
		}
		catch (DAOException e) {
			session.invalidate();
			System.out.println("Argh, probl�me DAO !");
			request.getRequestDispatcher("/JSP/ErreurDAO.jsp").forward(request, response);
		}
		catch (BadLoginException e) {
			session.invalidate();
			System.out.println("Argh, mauvais login !");
			request.getRequestDispatcher("/JSP/ErreurAuth.jsp").forward(request, response);
		}
		catch (BadPasswordException e) {
			session.invalidate();
			System.out.println("Argh, mauvais mot de passe !");
			request.getRequestDispatcher("/JSP/ErreurAuth.jsp").forward(request, response);
		}
	}
}
